/**
 * Created with Vim7.3 ubuntu12.04
 * @fileOverview : 
 * @author : Lyle <lylechen2014@gmial.com>
 * @since : 2014-12-17 23:00:08
 * @filename : app/modules/index/indexCtrl.js
 * @version : 
 * @description : 
 */

define(function (require, exports, module) {
  'use strict';

  var app = require('app');
      app.register.controller('signinCtrl', ['$scope','$location','$http','lang',function($scope,$location,$http,lang){
          $scope.lang = lang;
          $scope.submitForm = function(isValid,user) {
              console.log(isValid,user);
              $scope.userForm.submitted = false; 
              if (isValid) {
                   $http({method: 'POST', url: seajs.data.vars.apiUrl+'api.php', data:user, cache: true}).
                   success(function(data, status) {
                      $scope.status = status;
                      $scope.data = data;
                      if (user.name == 'angular' && user.password == '123456') {
                          $location.path('/center');
                      } else {
                          $scope.userForm.submitted = true; 
                      }
                   }).
                   error(function(data, status) {
                      $scope.data = data || "Request failed";
                      $scope.status = status;
                   });
              }
          } 
 
         }]
     );

     app.register.directive('myAccount', function(){
       var userNameExp = /^[a-zA-z]{1,}[a-zA-Z0-9_]*$/,
           emailExp = /^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/;
       return {
           require: 'ngModel', 
           link: function (scope, element, attrs, ngModel) {
             if(!ngModel) return;
                 ngModel.$parsers.unshift(function(viewValue){
                    if(userNameExp.test(viewValue)){
                      ngModel.$setValidity('myAccount',true);
                      return viewValue;
                    } else if (emailExp.test(viewValue)) {
                      ngModel.$setValidity('myAccount',true);
                      return viewValue;
                    } else {
                      ngModel.$setValidity('myAccount',false);
                      return undefined;
                    }
                 });
             }
       }
     });
});
